package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param loginDTO
     */
    @Override
    public User login(UserLoginDTO loginDTO) throws LoginException {

        String openid = getOpenId(loginDTO);
        if(null == openid || "".equals(openid)){
            throw new LoginException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getbyOpenId(openid);
        if(null == user){
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openid);

            userMapper.insert(user);
        }

        return user;
    }

    private String getOpenId(UserLoginDTO loginDTO) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();

        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", loginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(url, paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        return (String) jsonObject.get("openid");
    }
}
